const app = getApp();
// const URL = 'https://www.oybtrip.com';
const URL = app.globalData.URL;

let orderList = [
  {
    state: '自提',
    sum: '1096.00',
    total: 1,
    title: '租满即送（含电池租金）',
    description: '套餐：租满即送（含电池租金）12个月',
    zq:'2023.7.21-2024.7.21',
    price: '499.00',
    num: '1',
    isChecked: false,
    image:URL+'/admin-api/infra/file/4/get/b3a10951f9307d6b22e4f3880e2ff2fcd267d4fe68456077ded7a7d76f5e01ae.png',
  }
];

var orderSn = "";


function setTimeDateFmt(s) {  // 个位数补齐十位数
  return s < 10 ? '0' + s : s;
}
/**
 * #JS生成订单号的函数
 * @param 
 * 
 * @return string 生成的订单号
 * @https://www.73so.com
 */
function createordernum() 
{
    const now = new Date();
    let month = now.getMonth() + 1;
    let day = now.getDate();
    let hour = now.getHours();
    let minutes = now.getMinutes();
    let seconds = now.getSeconds();
    month = setTimeDateFmt(month);
    day = setTimeDateFmt(day);
    hour = setTimeDateFmt(hour);
    minutes = setTimeDateFmt(minutes);
    seconds = setTimeDateFmt(seconds);
    let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
    return orderCode;
}

import format from './utils';

Page({
  data: {
    tabs: ['租赁中'],
    activeTab: 0, 
    titleOpacity: 1,
    shadow: false,
    isChecked: false,
    orderList: orderList,
    orderList2:null,
    currentCommodity:null,
    paymentHistory: null, //支付历史记录
    isPaying: false, //支付状态
    uid: null, //用户ID
    isLogin: false //登录状态
  },
  onLoad(){
    console.log("获取传递参数商品");
    let params = my.getStorageSync({ key: 'params' }).data;
    this.setData({currentCommodity:params.currentCommodity});
    console.log(this.data.currentCommodity);

    // const history = this.getPaymentHistoryByUID(app.globalData.uid);
    // console.log("账单历史");
    // console.log(history);

    this.setData({
      paymentHistory: history,
      isLogin: app.globalData.isLogin,
      uid: app.globalData.uid
    });
    my.httpRequest({
      url: `${URL}/app-api/chl/order/listAllByPhone`,
      data: {
        phone:app.globalData.mobile,
      },
      headers:{"tenant-id":app.globalData.tenant_id,
      'content-type': 'application/x-www-form-urlencoded'},
      success: (res) => {
        console.log(app.globalData.mobile);
        console.log(res.data.data);
      },
      fail: (err) => {
        console.log(err);
      }
    });
  },
  /**
   * 信用免押
   */
  xymy(){
    console.log("信用免押");
    orderSn = createordernum();
    console.log(orderSn);
    //my.navigateTo({url:"/pages/pay/pay"});
    //周期扣款
    this.onClickHandlerMy();
    //新增订单
    //this.addOrder(orderSn);
  },

  /**
   * 创建订单
   */
  addOrder(tradeNo){
    console.log('信用免押成功，创建订单');

    console.log(createordernum());

    my.httpRequest({
      url: `${URL}/app-api/chl/order/create`,
      method: 'POST',
      data: {
        orderSn:orderSn,
        tradeNo:tradeNo,
        commodityId:this.data.currentCommodity.id,
        goodsName:this.data.currentCommodity.name,
        phone:app.globalData.mobile,
        name:app.globalData.name,
        zdzq:'1',
        mqzj:this.data.currentCommodity.mqzj,
        zzq:this.data.currentCommodity.qs,
        yjje:this.data.currentCommodity.yjje,
        zzf:this.data.currentCommodity.zzf,
        sxf:this.data.currentCommodity.sxf,
        orderStatus:'3',
      },
      headers:{"tenant-id":app.globalData.tenant_id,
      'content-type': 'application/json'},
      success: (res) => {
        console.log(app.globalData.mobile);
        console.log(res.data);
        //my.alert({'content':'订单创建成功'});
        my.navigateTo({url: "/pages/order/order"});
      },
      fail: (err) => {
        console.log(err);
      }
    });

  },

  /**
   * 周期扣款
   * //alipayTradeCreate
   * //alipayPaySign
   */
  zqkk(){
    my.request({
      url: `${URL}/app-api/chl/app/alipayPaySign`,
      method: 'GET',
      data: {
        out_trade_no:orderSn,
        subject:this.data.currentCommodity.guige,
        commodityId:this.data.currentCommodity.id,
        mqzj:this.data.currentCommodity.mqzj,
        zzj:this.data.currentCommodity.zzj,
        qs:this.data.currentCommodity.qs,
        zzf:this.data.currentCommodity.zzf,
        sxf:this.data.currentCommodity.sxf,
        buyer_id:app.globalData.uid,
      },
      headers:{"tenant-id":"1",
      'content-type': 'application/json'},
      success: (res) => {
        console.log("支付并签约success"+"用户ID"+app.globalData.uid);
        console.log(res.data.tradeNo);
        var tradeNo = String(res.data.tradeNo);

        my.tradePay({
          // 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
          tradeNO: tradeNo,
          success: (res) => {
            console.log("接口成功——"+JSON.stringify(res));
            if(res.resultCode=="9000"){
              my.alert({
                title:"成功",
                content: "支付成功",
              });
              this.addOrder(tradeNo);
            }else{
              my.alert({
                title:"支付失败",
                content: res.memo,
              });
            }
          },
          fail: (res) => {
            console.log("支付失败——"+JSON.stringify(res));
            my.alert({
              title:"支付失败",
              content: JSON.stringify(res),
            });
          }
        });
      },
      fail: (err) => {
        console.log("支付并签约error"+"用户ID"+app.globalData.uid);
        console.log(err);
      }
    });

  },
  //独立签约(预留)
  dlqy(){
    var signStr = '';
    my.request({
      url: `${URL}/app-api/chl/app/alipaySign`,
      method: 'GET',
      data: {
        out_trade_no:orderSn,
        subject:"橙黄蓝499元/期，共12期",
        total_amount:"0.05",
        buyer_id:app.globalData.uid,
      },
      headers:{"tenant-id":"1",
      'content-type': 'application/json'},
      success: (res) => {
        console.log("支付并签约success"+"用户ID"+app.globalData.uid);
        console.log(res.data);
        signStr = res.data;

        my.paySignCenter({
          signStr: signStr,
          success: function(res) {
           console.log(res);
         },
         fail: function(err) {
           console.log(err);
         }
       });
      },
      fail: (err) => {
        console.log("独立签约error"+"用户ID"+app.globalData.uid);
        console.log(err);
      }
    });
   
  },
  //联系租户
  lxzh(){
    my.makePhoneCall(
      {
      number: '17797713158', 
      success: function(res) 
      {
       console.log(res); 
      },
      fail: function(err) {
        console.log(err); 
      }
      }
      );
  },
  onTabBarTap(e) {
    const { index } = e.target.dataset
    let sList = []
    if(index == 0){
      sList = orderList
    }else if(index == 1){
      sList[0] = orderList[0]
    }else if(index == 2){
      sList[0] = orderList[1]
    }else if(index == 3){
      sList[0] = orderList[2]
    }else if(index == 4){
      sList[0] = orderList[3]
    }else if(index == 5){
      sList[0] = orderList[4]
    }
    this.setData({
      activeTab: index,
      orderList: sList
    });
  },
  viewService() {
    my.navigateTo({
      url: '/pages/service/service',
    })
  },
  checkService() {
    this.setData({
      isChecked: !this.data.isChecked
    })
  },
  // 申请免押金
  onClickHandlerMy() {
    this.setData({
      isPaying: true
    })
    if(!app.globalData.isLogin) {
      // 未登录时
      my.navigateTo({
        url: '/pages/mine/components/sq/sq',
      })
    }else {
      if(this.data.isChecked) {
        // 已经勾选，正常走流程
        //周期扣款
        this.zqkk();
        //this.dlqy();
      }else {
        my.alert({
          title: '提示',
          content: '请先勾选租赁服务'
        })
      }
    }
  },
  // 支付订单
  handlePay() {
    if(!app.globalData.isLogin) {
      // 未登录时
      my.navigateTo({
        url: '/pages/mine/components/sq/sq',
      })
    }else {
      if(this.data.isChecked) {
        // 已勾选，正常支付
        this.onClickHandler();
        
      }else {
        my.alert({
          title: '',
          content: '请先勾选租赁服务'
        })
      }
    }
  },
  
  //支付逻辑------------------------------

   /**
   *  @name onClickHandler
   *  @description 查看/支付按钮操作
   */
  async onClickHandler() {
    this.setData({
      isPaying: true
    });
    if (!this.data.isLogin) {
      //未登录状态
      try {
        const auth = await this.getAuthCode('auth_user');
        const user = await this.getUserByAuthCode(auth.authCode);
        const history = await this.getPaymentHistoryByUID(user.userId);
        this.setData({
          isPaying: false,
          paymentHistory: history,
          isLogin: true,
          uid: user.userId
        });
      } catch (error) {
        this.setData({
          isPaying: false
        });
        this.showToast(error.message, 'exception');
      }
    } else {
      // 已登录
      try {
        const auth = await this.getAuthCode('auth_user');
        const trade = await this.getTradeNo(auth.authCode, this.data.uid);
        const payStatus = await this.cashPaymentTrade(trade.tradeNo);
        this.showToast(payStatus.message);
        const updatePayment = await this.updatePaymentListByTradeNo(trade.tradeNo);
        this.setData({
          paymentHistory: updatePayment,
          isPaying: false
        });
      } catch (error) {
        this.setData({
          isPaying: false
        });
        this.showToast(error.message, 'exception');
      }
    }
  },

  /**
   * @name onRefundPayHandler
   * @description 发起退款
   * @param {*} event
   */
  async onRefundPayHandler(event) {
    const { key } = event.target.dataset;
    const refundItem = await this.findActiveTradeByNo(key);
    try {
      if (refundItem !== null) {
        const refundOrder = await this.refundPaymentByTradeNo(
          refundItem.tradeNo,
          refundItem.totalAmount
        );
        const updatePayment = await this.updatePaymentListByTradeNo(refundOrder.tradeNo);
        this.showToast('退款成功');
        this.setData({
          paymentHistory: updatePayment
        });
      } else {
        this.showToast('未知支付订单', 'exception');
      }
    } catch (error) {
      this.showToast(error.message, 'exception');
    }
  },
  /**
   * @name onRepeatPayHandler
   * @description 列表重新付款
   * @param {*} event
   */
  async onRepeatPayHandler(event) {
    const { key } = event.target.dataset;
    const repeatItem = await this.findActiveTradeByNo(key);
    try {
      if (repeatItem !== null) {
        const payStatus = await this.cashPaymentTrade(repeatItem.tradeNo);
        this.showToast(payStatus.message);
        const updatePayment = await this.updatePaymentListByTradeNo(repeatItem.tradeNo);
        this.setData({
          paymentHistory: updatePayment
        });
      } else {
        this.showToast('未知支付订单', 'exception');
      }
    } catch (error) {
      this.showToast(error.message, 'exception');
    }
  },
  /**
   * @name findActiveTradeByNo
   * @description 查找当前操作项
   * @param {*} tradeNo
   * @returns
   */
  async findActiveTradeByNo(tradeNo) {
    const findItem = this.data.paymentHistory.find((item) => {
      return item.key === tradeNo;
    });
    if (findItem !== undefined) {
      findItem.actionStatus = true;
      this.setData({
        paymentHistory: this.data.paymentHistory
      });
      return findItem;
    } else {
      return null;
    }
  },

  /**
   * @name updatePaymentListByTradeNo
   * @description 根据tradeNo更新列表数据
   * @param {*} tradeNo
   * @returns
   */
  async updatePaymentListByTradeNo(tradeNo) {
    let isExistOrder = false;
    const order = await this.queryPaymentByTradeNo(tradeNo);
    const formatHistory = this.data.paymentHistory.map((item) => {
      if (item.tradeNo === order.tradeNo) {
        isExistOrder = true;
        item.key = order.tradeNo;
        item.tradeNo = order.tradeNo;
        item.actionStatus = false;
        item.totalAmount = order.totalAmount;
        item.tradeStatus = order.tradeStatus;
        item.viewTime = format(order.sendPayDate, 'yyyy-MM-dd hh:mm:ss');
      }
      return item;
    });
    if (!isExistOrder) {
      const addOrder = {};
      addOrder.key = order.tradeNo;
      addOrder.actionStatus = false;
      addOrder.tradeNo = order.tradeNo;
      addOrder.totalAmount = order.totalAmount;
      addOrder.tradeStatus = order.tradeStatus;
      addOrder.viewTime = format(order.sendPayDate, 'yyyy-MM-dd hh:mm:ss');
      formatHistory.unshift(addOrder);
    }
    return formatHistory;
  },

  /***************************/
  /******* 封装服务端 API ******/
  /***************************/
  /**
   * @name getUserByAuthCode
   * @description 获取用户信息
   * @param {*} authCode
   * @returns
   */
  getUserByAuthCode(authCode) {
    return new Promise((resolve, reject) => {
      my.request({
        url: `${URL}/app-api/chl/app/alipayUserInfo`,
        data: {
          authCode: authCode
        },
        headers:{"tenant-id":"1"},
        success: (result) => {
          if (!result.data.success) {
            reject({
              ...result.data,
              message: '获取用户信息失败'
            });
          }
          resolve(result.data);
        },
        fail: (err) => {
          reject({
            ...err,
            message: '获取用户信息异常'
          });
        }
      });
    });
  },
  /**
   * @name getPaymentHistoryByUID
   * @description 获取登录用户的支付历史记录
   * @param {*} uid
   * @returns {Array/object}
   */
  getPaymentHistoryByUID(uid) {
    return new Promise((resolve, reject) => {
      my.request({
        url: `${URL}/app-api/chl/app/userPay`,
        headers: {
          "tenant-id":"1",
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          userId: uid
        },
        success: (result) => {
          if (!result.data.success) {
            reject({
              ...result.data,
              message: '获取支付历史失败'
            });
          } else {
            const formatHistory = result.data.alipayTradeQueryList.map((item) => {
              const order = {};
              order.key = item.tradeNo;
              order.tradeNo = item.tradeNo;
              order.actionStatus = false;
              order.totalAmount = item.totalAmount;
              order.tradeStatus = item.tradeStatus;
              order.viewTime = format(item.sendPayDate, 'yyyy-MM-dd hh:mm:ss');
              return order;
            });
            resolve(formatHistory);
          }
        },
        fail: (err) => {
          reject({
            ...err,
            message: '获取支付历史异常'
          });
        }
      });
    });
  },
  /**
   * @name getTradeNo
   * @description 创建支付交易订单
   * @param {*} authCode
   * @param {*} uid
   * @returns {object}
   */
  getTradeNo(authCode, uid) {
    return new Promise((resolve, reject) => {
      my.request({
        url: `${URL}/app-api/chl/app/alipayTradeCreate`,
        data: {
          total_amount: '591',
          out_trade_no: `${new Date().getTime()}_demo_pay`,
          scene: 'bar_code',
          auth_code: authCode,
          subject: '小程序支付演示DEMO',
          buyer_id: uid
        },
        headers:{"tenant-id":"1"},
        success: (result) => {
          if (!result.data.success) {
            reject({
              ...result.data,
              message: '创建支付订单失败'
            });
          } else {
            resolve(result.data);
          }
        },
        fail: (err) => {
          reject({
            ...err,
            message: '创建支付订单异常'
          });
        }
      });
    });
  },
  /**
   * @name queryPaymentByTradeNo
   * @description 查询单笔订单
   * @param {*} tradeNo
   * @returns
   */
  queryPaymentByTradeNo(tradeNo) {
    return new Promise((resolve, reject) => {
      my.request({
        url: `${URL}/app-api/chl/app/alipayTradeQuery`,
        data: {
          trade_no: tradeNo
        },
        headers:{"tenant-id":"1"},
        success: (result) => {
          if (!result.data.success) {
            reject({
              message: '支付查询失败',
              ...result.data
            });
          } else {
            resolve(result.data);
          }
        },
        fail: (err) => {
          reject({
            message: '支付查询异常',
            ...err
          });
        }
      });
    });
  },
  /**
   * @name refundPaymentByTradeNo
   * @description 退款流程
   * @param {*} tradeNo
   * @param {*} refundAmount
   */
  refundPaymentByTradeNo(tradeNo, refundAmount) {
    return new Promise((resolve, reject) => {
      my.request({
        url: `${URL}/app-api/chl/app/alipayTradeRefund`,
        data: {
          trade_no: tradeNo,
          refund_amount: refundAmount
        },
        headers:{"tenant-id":"1"},
        success: (result) => {
          if (!result.data.success) {
            reject({
              message: '退款失败',
              ...result.data
            });
          } else {
            resolve(result.data);
          }
        },
        fail: (err) => {
          reject({
            message: '退款异常',
            ...err
          });
        }
      });
    });
  },

  /***************************/
  /******* 封装小程序 API ******/
  /***************************/
  /**
   * @name getAuthCode
   * @description 获取用户授权
   * @param {string} [scopeCode='auth_user']
   * @returns {object}
   */
  getAuthCode(scopeCode = 'auth_user') {
    return new Promise((resolve, reject) => {
      my.getAuthCode({
        scopes: scopeCode,
        success: (auth) => {
          resolve(auth);
        },
        fail: (err) => {
          reject({ ...err, message: '获取用户授权失败' });
        }
      });
    });
  },
  /**
   * @name cashPaymentTrade
   * @description 发起支付
   * @param {*} tradeNo
   * @returns
   */
  cashPaymentTrade(tradeNo) {
    return new Promise((resolve, reject) => {
      my.tradePay({
        tradeNO: tradeNo,
        success: (result) => {
          if (result.resultCode != 9000) {
            resolve({
              status: false,
              message: result.memo,
              ...result
            });
          } else {
            resolve({
              status: true,
              message: '支付成功',
              ...result
            });
          }
        },
        fail: (err) => {
          reject({
            status: false,
            message: '支付异常',
            ...err
          });
        }
      });
    });
  },
  /**
   * @name showToast
   * @description 通用提示信息
   * @param {*} message
   * @param {string} [type='none']
   */
  showToast(message, type = 'none') {
    my.showToast({
      type,
      content: message,
      duration: 3000
    });
  }
  
});
